package com.gs.SynAntiWandering.util;

import android.app.Activity;
import android.os.Build;

import com.gs.SynAntiWandering.constant.AllConstants;

import java.util.ArrayList;
import java.util.List;

public class ActivityUtil {
    private List<Activity> activityList;

    private static volatile ActivityUtil instance;

    public ActivityUtil() {
        activityList = new ArrayList<>();
    }

    public static ActivityUtil getInstance() {
        if (instance == null) {
            synchronized (ActivityUtil.class) {
                if (instance == null) {
                    instance = new ActivityUtil();
                }
            }
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        if (!activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    public void removeActivity(Activity activity) {
        if (activityList != null && !activityList.isEmpty()) {
            activityList.remove(activity);
            activity = null;
        }
    }

    public void finishActivity() {
        SPUtil.getInstance().putString(AllConstants.TOKEN, "");
        SPUtil.getInstance().putString(AllConstants.REFRESH_TOKEN, "");
        SPUtil.getInstance().putString(AllConstants.SITE_ID, "");
        SPUtil.getInstance().putString(AllConstants.SITE_NAME, "");
        SPUtil.getInstance().putString(AllConstants.ID, "");
        SPUtil.getInstance().putInt(AllConstants.LANGUAGE, 1);
        if (activityList != null && !activityList.isEmpty()) {
            for (Activity activity : activityList) {
                activity.finish();
                activity = null;
            }
            activityList.clear();
        }
    }

    public boolean isSurvive(Activity activity) {
        return activity != null && !activity.isFinishing() &&
                (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 ||
                        !activity.isDestroyed());
    }
}
